<template>
  <div class="income-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">本月收入</div>
              <div class="data-value">¥{{ statistics.monthIncome }}</div>
              <div class="data-compare">
                较上月
                <span :class="statistics.monthCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.monthCompare >= 0 ? '+' : '' }}{{ statistics.monthCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#409EFF"><Money /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">本周收入</div>
              <div class="data-value">¥{{ statistics.weekIncome }}</div>
              <div class="data-compare">
                较上周
                <span :class="statistics.weekCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.weekCompare >= 0 ? '+' : '' }}{{ statistics.weekCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#67C23A"><Tickets /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">今日收入</div>
              <div class="data-value">¥{{ statistics.todayIncome }}</div>
              <div class="data-compare">
                较昨日
                <span :class="statistics.todayCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.todayCompare >= 0 ? '+' : '' }}{{ statistics.todayCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#E6A23C"><Calendar /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">可提现金额</div>
              <div class="data-value">¥{{ statistics.availableMoney }}</div>
              <div class="data-compare">
                <el-button type="primary" size="small" @click="showWithdrawDialog">提现</el-button>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#F56C6C"><Wallet /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入图表和提现记录 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 收入趋势图 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收入趋势</span>
              <el-radio-group v-model="incomeChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="incomeChartRef"></div>
        </el-card>
      </el-col>
      
      <!-- 提现记录 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="withdraw-card">
          <template #header>
            <div class="card-header">
              <span>提现记录</span>
              <el-button type="text" @click="viewAllWithdraws">查看全部</el-button>
            </div>
          </template>
          <div class="withdraw-list">
            <div v-if="withdrawRecords.length === 0" class="no-data">
              暂无提现记录
            </div>
            <div v-for="record in withdrawRecords" :key="record.id" class="withdraw-item">
              <div class="withdraw-info">
                <div class="withdraw-amount">¥{{ record.amount.toFixed(2) }}</div>
                <div class="withdraw-status">
                  <el-tag v-if="record.status === 'success'" type="success" size="small">成功</el-tag>
                  <el-tag v-else-if="record.status === 'pending'" type="warning" size="small">处理中</el-tag>
                  <el-tag v-else-if="record.status === 'failed'" type="danger" size="small">失败</el-tag>
                </div>
              </div>
              <div class="withdraw-detail">
                <div class="withdraw-time">{{ record.time }}</div>
                <div class="withdraw-account">{{ record.account }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入明细 -->
    <el-card class="mt-20 income-detail-card">
      <template #header>
        <div class="card-header">
          <span>收入明细</span>
          <div class="header-actions">
            <el-select v-model="detailFilter" placeholder="筛选" size="small" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all" />
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
            </el-select>
            <el-button type="primary" size="small" @click="exportIncome">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="income-detail-list">
        <el-table
          :data="incomeDetails"
          stripe
          border
          style="width: 100%"
          v-loading="detailLoading"
        >
          <el-table-column prop="date" label="日期" width="120" sortable />
          <el-table-column prop="orderCount" label="订单数" width="100" sortable />
          <el-table-column prop="totalAmount" label="收入金额" width="120" sortable>
            <template #default="scope">
              ¥{{ scope.row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="platformFee" label="平台服务费" width="120">
            <template #default="scope">
              ¥{{ scope.row.platformFee.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="taxFee" label="税费" width="100">
            <template #default="scope">
              ¥{{ scope.row.taxFee.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="actualAmount" label="实际收入" width="120">
            <template #default="scope">
              ¥{{ scope.row.actualAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'settled'" type="success">已结算</el-tag>
              <el-tag v-else-if="scope.row.status === 'pending'" type="warning">待结算</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                @click="showIncomeDetailDialog(scope.row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="申请提现"
      width="500px"
    >
      <el-form :model="withdrawForm" label-width="100px" :rules="withdrawRules" ref="withdrawFormRef">
        <el-form-item label="可提现金额">
          <span class="available-money">¥{{ statistics.availableMoney }}</span>
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model.number="withdrawForm.amount" type="number" placeholder="请输入提现金额">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="提现方式" prop="method">
          <el-radio-group v-model="withdrawForm.method">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信</el-radio>
            <el-radio label="bank">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款账号" prop="account">
          <el-input v-model="withdrawForm.account" placeholder="请输入收款账号" />
        </el-form-item>
        <el-form-item label="支付密码" prop="password">
          <el-input v-model="withdrawForm.password" type="password" placeholder="请输入支付密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitWithdraw">确认提现</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 收入详情对话框 -->
    <el-dialog
      v-model="incomeDetailDialogVisible"
      title="收入详情"
      width="700px"
    >
      <div v-if="selectedIncomeDetail" class="income-detail-dialog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日期">{{ selectedIncomeDetail.date }}</el-descriptions-item>
          <el-descriptions-item label="订单数">{{ selectedIncomeDetail.orderCount }}</el-descriptions-item>
          <el-descriptions-item label="收入金额">¥{{ selectedIncomeDetail.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="平台服务费">¥{{ selectedIncomeDetail.platformFee.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="税费">¥{{ selectedIncomeDetail.taxFee.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="实际收入">¥{{ selectedIncomeDetail.actualAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="结算状态">
            <el-tag v-if="selectedIncomeDetail.status === 'settled'" type="success">已结算</el-tag>
            <el-tag v-else-if="selectedIncomeDetail.status === 'pending'" type="warning">待结算</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="结算时间" v-if="selectedIncomeDetail.settleTime">
            {{ selectedIncomeDetail.settleTime }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider>订单明细</el-divider>
        
        <el-table :data="selectedIncomeDetail.orders || []" stripe border style="width: 100%">
          <el-table-column prop="id" label="订单号" width="120" />
          <el-table-column prop="time" label="订单时间" width="150" />
          <el-table-column prop="passengerName" label="乘客" width="100" />
          <el-table-column prop="route" label="行程" />
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="scope">
              ¥{{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 统计数据
const statistics = reactive({
  monthIncome: 4589.75,
  monthCompare: 5.2,
  weekIncome: 1234.56,
  weekCompare: 3.8,
  todayIncome: 345.5,
  todayCompare: -2.1,
  availableMoney: 3850.25
})

// 收入图表相关
const incomeChartRef = ref(null)
let incomeChart = null
const incomeChartType = ref('month')

// 收入明细相关
const detailLoading = ref(false)
const detailFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 收入详情对话框
const incomeDetailDialogVisible = ref(false)
const selectedIncomeDetail = ref(null)

// 提现对话框
const withdrawDialogVisible = ref(false)
const withdrawFormRef = ref(null)
const withdrawForm = reactive({
  amount: '',
  method: 'alipay',
  account: '',
  password: ''
})

// 提现表单验证规则
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', message: '金额必须为数字', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('提现金额必须大于0'))
        } else if (value > statistics.availableMoney) {
          callback(new Error('提现金额不能大于可提现金额'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  method: [
    { required: true, message: '请选择提现方式', trigger: 'change' }
  ],
  account: [
    { required: true, message: '请输入收款账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
  ]
}

// 收入明细数据
const incomeDetails = ref([
  {
    date: '2023-05-10',
    orderCount: 8,
    totalAmount: 345.5,
    platformFee: 34.55,
    taxFee: 17.28,
    actualAmount: 293.67,
    status: 'settled',
    settleTime: '2023-05-11 00:30:00',
    orders: [
      { id: 'O2023051001', time: '2023-05-10 08:30', passengerName: '李同学', route: '校园北门 → 火车站', amount: 25.5 },
      { id: 'O2023051002', time: '2023-05-10 10:15', passengerName: '王同学', route: '图书馆 → 华联商场', amount: 18.0 },
      { id: 'O2023051003', time: '2023-05-10 14:45', passengerName: '赵同学', route: '学生公寓 → 市中心', amount: 35.0 }
    ]
  },
  {
    date: '2023-05-09',
    orderCount: 6,
    totalAmount: 280.0,
    platformFee: 28.0,
    taxFee: 14.0,
    actualAmount: 238.0,
    status: 'settled',
    settleTime: '2023-05-10 00:30:00',
    orders: []
  },
  {
    date: '2023-05-08',
    orderCount: 7,
    totalAmount: 310.5,
    platformFee: 31.05,
    taxFee: 15.53,
    actualAmount: 263.92,
    status: 'settled',
    settleTime: '2023-05-09 00:30:00',
    orders: []
  },
  {
    date: '2023-05-07',
    orderCount: 5,
    totalAmount: 245.0,
    platformFee: 24.5,
    taxFee: 12.25,
    actualAmount: 208.25,
    status: 'settled',
    settleTime: '2023-05-08 00:30:00',
    orders: []
  },
  {
    date: '2023-05-06',
    orderCount: 9,
    totalAmount: 398.5,
    platformFee: 39.85,
    taxFee: 19.93,
    actualAmount: 338.72,
    status: 'settled',
    settleTime: '2023-05-07 00:30:00',
    orders: []
  }
])

// 计算总数
total.value = incomeDetails.value.length

// 提现记录
const withdrawRecords = ref([
  {
    id: 'W20230508001',
    amount: 1000.0,
    status: 'success',
    time: '2023-05-08 14:30',
    account: '支付宝 (186****1234)'
  },
  {
    id: 'W20230501001',
    amount: 2000.0,
    status: 'success',
    time: '2023-05-01 10:15',
    account: '银行卡 (尾号3456)'
  },
  {
    id: 'W20230425001',
    amount: 1500.0,
    status: 'success',
    time: '2023-04-25 16:45',
    account: '微信 (微信号)'
  }
])

// 监听图表类型变化
watch(incomeChartType, (newVal) => {
  initIncomeChart()
})

// 初始化收入图表
const initIncomeChart = () => {
  if (!incomeChartRef.value) return
  
  if (incomeChart) {
    incomeChart.dispose()
  }
  
  incomeChart = echarts.init(incomeChartRef.value)
  
  let xAxisData = []
  let seriesData = []
  
  if (incomeChartType.value === 'week') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    seriesData = [120, 132, 101, 134, 90, 230, 210]
  } else if (incomeChartType.value === 'month') {
    xAxisData = Array.from({length: 30}, (_, i) => i + 1)
    seriesData = [
      120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 
      134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 
      210, 120, 132, 101, 134, 90, 230, 210, 120, 132
    ]
  } else {
    xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    seriesData = [900, 850, 950, 1000, 1100, 1050, 1000, 1150, 1250, 1370, 1250, 1100]
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'line',
        smooth: true,
        data: seriesData,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  incomeChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    incomeChart.resize()
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchIncomeDetails()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchIncomeDetails()
}

// 获取收入明细
const fetchIncomeDetails = () => {
  detailLoading.value = true
  // 模拟API请求
  setTimeout(() => {
    // 这里实际项目中应该调用API
    detailLoading.value = false
  }, 500)
}

// 显示提现对话框
const showWithdrawDialog = () => {
  withdrawDialogVisible.value = true
  withdrawForm.amount = ''
  withdrawForm.account = ''
  withdrawForm.password = ''
}

// 提交提现
const submitWithdraw = async () => {
  try {
    await withdrawFormRef.value.validate()
    
    // 模拟API请求
    // 在实际项目中，应该调用API提交提现申请
    
    ElMessage.success('提现申请已提交，请等待处理')
    withdrawDialogVisible.value = false
    
    // 添加提现记录（模拟）
    const account = getAccountDisplay(withdrawForm.method, withdrawForm.account)
    withdrawRecords.value.unshift({
      id: 'W' + new Date().getTime(),
      amount: withdrawForm.amount,
      status: 'pending',
      time: new Date().toLocaleString(),
      account: account
    })
    
    // 减少可提现金额（模拟）
    statistics.availableMoney -= withdrawForm.amount
    
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 获取账号显示名称
const getAccountDisplay = (method, account) => {
  if (method === 'alipay') {
    return `支付宝 (${maskAccount(account)})`
  } else if (method === 'wechat') {
    return `微信 (${maskAccount(account)})`
  } else if (method === 'bank') {
    return `银行卡 (尾号${account.slice(-4)})`
  }
  return account
}

// 掩码账号
const maskAccount = (account) => {
  if (account.length <= 4) return account
  return account.substring(0, 3) + '****' + account.substring(account.length - 4)
}

// 查看全部提现记录
const viewAllWithdraws = () => {
  ElMessage.info('查看全部提现记录')
}

// 导出收入明细
const exportIncome = () => {
  ElMessage.success('收入明细已导出')
}

// 显示收入详情对话框
const showIncomeDetailDialog = (detail) => {
  selectedIncomeDetail.value = detail
  incomeDetailDialogVisible.value = true
}

// 组件挂载后执行
onMounted(() => {
  initIncomeChart()
  fetchIncomeDetails()
})
</script>

<style scoped>
.income-container {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
}

.data-card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  height: 100%;
}

.data-card-left {
  display: flex;
  flex-direction: column;
}

.data-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.data-compare {
  font-size: 12px;
  color: #909399;
}

.data-compare .up {
  color: #67C23A;
}

.data-compare .down {
  color: #F56C6C;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.withdraw-list {
  max-height: 300px;
  overflow-y: auto;
}

.withdraw-item {
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
}

.withdraw-item:last-child {
  border-bottom: none;
}

.withdraw-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.withdraw-amount {
  font-size: 18px;
  font-weight: bold;
}

.withdraw-detail {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.available-money {
  font-size: 18px;
  font-weight: bold;
  color: #F56C6C;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #909399;
  font-size: 14px;
}

.income-detail-dialog {
  max-height: 60vh;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .chart-container {
    height: 200px;
  }
}
</style> 